package com.haruhi.Interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haruhi.entity.vo.ResponseEntity;
import com.haruhi.utils.ParamUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 * 管理端的拦截
 * 没必要做太复杂
 */
public class ManageInterceptor implements HandlerInterceptor {

    private static final String MANAGE_TOKEN = "manage_token";
    private String username;

    public void setUsername(String username){
        this.username = username;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String manage_token = request.getHeader(MANAGE_TOKEN);
        if(!ParamUtil.isEmpty(manage_token) && username.equals(manage_token)){
            return true;
        }

        ResponseEntity result = new ResponseEntity(-401,"请求被拦截",null);
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().print(json);
        return false;
    }
}
